<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1 class="m-0 text-dark">用户管理</h1>
      </div><!-- /.col -->
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a th:href="@{../admin}">首页</a></li>
          <li class="breadcrumb-item active">系统管理</li>
          <li class="breadcrumb-item active">用户管理</li>
        </ol>
      </div><!-- /.col -->
    </div><!-- /.row -->
  </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
  <div class="card card-info">
    <shiro:hasPermission name="user:list">
      <form id="searchForm" class="needs-validation form-inline" novalidate="">
        <div class="form-group">
          <label for="username" class="mr-2">用户名</label>
          <input type="text" class="form-control" id="username">
        </div>
        <div class="form-group ml-3">
          <label for="mobile" class="mr-2">电话</label>
          <input type="tel" class="form-control" id="mobile">
        </div>
        <div class="form-group">
          <button class="btn btn-primary ml-3" type="submit">查询</button>
          <button class="btn btn-default ml-2" type="reset">重置</button>
        </div>
      </form>
    </shiro:hasPermission>
  </div>
  <div class="card card-body">
    <div id="toolbar" class="btn-group">
      <shiro:hasPermission name="user:add">
        <button id="btn_add" type="button" class="btn btn-primary">
          <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
      </shiro:hasPermission>
      <shiro:hasPermission name="user:delete">
        <button id="btn_batch_delete" type="button" class="btn btn-danger ml-2">
          <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>批量删除
        </button>
      </shiro:hasPermission>
    </div>
    <table class="table-sm" id="table"></table>
  </div>
</section>


<!-- 表单模态框 -->
<section id="formModalWrapper">
  <div class="modal fade" id="formModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="formTitle"></h5>
          <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div id="formContent"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="saveOrUpdateBtn">保存
          </button>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- 角色分配模态框 -->
<section id="assignRoleModalWrapper">
  <div class="modal fade" id="assignRoleModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="assignRoleTitle">分配角色</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <!--                    <table id="assignRoleTable"></table>-->
          <div id="assignForm"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="assignRoleSaveOrUpdateBtn">保存
          </button>
        </div>
      </div>
    </div>
  </div>
</section>

<script>

  $(function () {

    var editFlag = Core.parseBool("[[${@perms.hasPerm('user:edit')}]]");
    var deleteFlag = Core.parseBool("[[${@perms.hasPerm('user:delete')}]]");
    var assignRoleFlag = Core.parseBool("[[${@perms.hasPerm('user:assign')}]]");
    var resetPasswordFlag = Core.parseBool("[[${@perms.hasPerm('user:resetPassword')}]]");

    window.operateEvents = {
      // 点击编辑
      'click .btn_edit': function (e, value, row, index) {
        editRow(row.id)
      },
      // 点击分配角色
      'click .btn_assign': function (e, value, row, index) {
        assignRole(row.id)
      },
      // 点击重置密码
      'click .btn_reset': function (e, value, row, index) {
        resetRow(row.id)
      },
      // 点击删除
      'click .btn_del': function (e, value, row, index) {
        deleteRow(row.id)
      }
    }
    var columns = [
      {checkbox: true},
      {
        field: 'username',
        title: '用户名',
        align: "center"
      }, {
        field: 'mobile',
        title: '电话',
        align: "center",
      }, {
        field: 'roleName',
        title: '角色',
        align: "center",
      }, {
        field: 'createTime',
        title: '创建时间',
        align: "center",
      }, {
        field: 'updateTime',
        title: '修改时间',
        align: "center",
      }, {
        field: 'operation',
        title: '操作',
        align: "center",
        width: 300,
        events: operateEvents,
        formatter: operationFormatter
      }];

    function operationFormatter(value, row, index) {
      var edit = editFlag ? '<button class="btn-plain btn_edit">编辑</button>' : '';
      var assign = assignRoleFlag ? '<button class="btn-plain btn_assign">分配角色</button>' : '';
      var reset = resetPasswordFlag ? '<button class="btn-plain btn_reset">重置密码</button>' :
        '';
      var del = deleteFlag ? '<button class="btn-plain btn_del">删除</button>' : '';
      return edit + assign + reset + del;
    }

    var options = {
      id: "#table",
      url: '/sys/user',
      columns: columns,
      toolbar: '#toolbar',
      showRefresh: true,
      queryParams: queryParams
    }
    Core.initTable(options);

    function refreshTable() {
      Core.refreshTable("#table")
    }

    // 查询参数
    function queryParams(params) {
      return {
        page: params.pageNumber,
        size: params.pageSize,
        username: $("#username").val(),
        mobile: $("#mobile").val()
      };
    }

    // 查询
    $('#searchForm').submit(function (event) {
      event.preventDefault();
      event.stopPropagation();
      refreshTable();
    })

    // 新增
    $('#btn_add').on('click', function () {
      Core.load("#formContent", "/load/user", function () {
        $('#formTitle').text('新增')
        $("#formModal").modal('show');
      }, 2);
    })

    // 编辑
    function editRow(id) {
      Core.load("#formContent", "/load/user/" + id, function () {
        $('#formTitle').text('编辑')
        $("#formModal").modal('show');
      }, 2);
    }

    // 删除
    function deleteRow(id) {
      Core.confirm("确定删除？", function () {
        Core.deleteAjax("/sys/user", {"ids": id}, function (data) {
          if (data.code === 1) {
            layer.msg('删除成功');
            refreshTable();
          } else {
            layer.msg(data.message);
          }
        })
      })
    }

    // 批量删除
    $("#btn_batch_delete").on('click', function () {
      var checkedRows = Core.selectMutiData("#table");
      if (checkedRows) {
        Core.confirm("确定删除选中的" + checkedRows.length + "条记录？", function () {
          var ids = [];
          $.each(checkedRows, function (i, item) {
            ids.push(item.id);
          })
          Core.deleteAjax("/sys/user", {"ids": ids}, function (data) {
            if (data.code === 1) {
              refreshTable();
              layer.msg("批量删除成功");
            } else {
              layer.msg(data.message);
            }
          })
        })
      }
    })

    /**
     * 重置用户密码
     * @param id 用户id
     */
    function resetRow(id) {
      Core.confirm("确定要重置该用户的密码？", function () {
        Core.putAjax("/auth/resetPassword", {"id": id}, function (data) {
          if (data.code === 1) {
            refreshTable();
            layer.msg('重置成功');
          } else {
            layer.msg(data.message);
          }
        })
      })
    }

    // 保存或更新
    $('#saveOrUpdateBtn').on('click', function () {
      var $f = $('#userForm');
      var valid = $f[0].checkValidity();
      var url = "/sys/user";
      var method = $f.find("input[name='id']").val() ? Core.putAjax : Core.postAjax;
      var data = {
        id: $f.find("input[name='id']").val(),
        username: $f.find("input[name='username']").val(),
        mobile: $f.find("input[name='mobile']").val()
      }
      if (valid) {
        Core.mask("#saveOrUpdateBtn");
        method(url, data, function (data) {
          Core.unmask("#saveOrUpdateBtn");
          if (data.code === 1) {
            $("#formModal").modal("hide");
            refreshTable();
            layer.msg("保存成功");
          } else {
            layer.msg(data.message);
          }
        }, function () {
          Core.unmask("#saveOrUpdateBtn");
        })
      }
      $f.addClass("was-validated")
    })

    var userIdChecked;

    // 分配角色
    function assignRole(userId) {
      userIdChecked = userId;
      Core.load("#assignForm", "/load/user/assign/" + userIdChecked);
      $("#assignRoleModal").modal("show");
    }

    $('#assignRoleSaveOrUpdateBtn').on('click', function () {
      let roleId = $('input[name="roleId"]:checked').val();
      if (!roleId) {
        layer.msg("请选择角色后提交");
        return;
      }
      let data = {
        userId: userIdChecked,
        roleId: roleId
      }
      Core.putAjax('/sys/user/assign', data, function (data) {
        Core.unmask("#assignRoleSaveOrUpdateBtn");
        if (data.code === 1) {
          $("#assignRoleModal").modal("hide");
          Core.refreshTable("#table");
          layer.msg("角色分配成功");
        } else {
          layer.msg(data.message);
        }
      }, function (xhr) {
        Core.unmask("#assignPermissionSaveOrUpdateBtn");
        console.log(xhr)
        layer.msg('保存失败')
      })
    })
  });
</script>